package org.xbl.xchain.sdk.utils;

import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class JsonRpcClientHelper {

    private static Proxy netProxy;
    private static Map<String, String> headers = new HashMap<>();

    static {
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyPort) && StringUtils.isNotBlank(proxyHost)) {
            netProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
        }
        headers.put("Content-Type", "text/json;charset=UTF-8");
    }

    public static JsonRpcHttpClient getClient(String rpcUrl) throws MalformedURLException {
        JsonRpcHttpClient jsonRpcHttpClient = new JsonRpcHttpClient(new URL(rpcUrl), headers);
        if (netProxy != null) {
            jsonRpcHttpClient.setConnectionProxy(netProxy);
        }
        return jsonRpcHttpClient;
    }
}
